import 'package:wu_you/model/user/user_model.dart';

import '../db.dart';

class LoginHistoryDao {
  factory LoginHistoryDao() => _getInstance();
  static LoginHistoryDao _instance;

  LoginHistoryDao._internal();

  static LoginHistoryDao _getInstance() {
    if (_instance == null) {
      _instance = LoginHistoryDao._internal();
    }
    return _instance;
  }

  static const _TABLE_NAME = "login_history";


  ///获取全部可用数据
  Future<List<UserPsw>> getAll() async {
    var db = await DatabaseHelper().db();
    // List<Map<String, Object>> list = await db.rawQuery('select * from login_history order by login_count desc');
    List<Map<String, Object>> result = await db.query(
      _TABLE_NAME,
      columns: ["user_name",'pass_word'],
      orderBy: 'login_count desc',
    );
    return result.map((e) => UserPsw.fromDB(e)).toList();
  }

  ///插入新数据
  ///如果存在则更新登录次数
  Future<int> insert(String username,String password) async {
    var db = await DatabaseHelper().db();
    int result = 0;
    int count = await db.rawUpdate("update login_history set login_count = login_count + 1 where user_name = ? and pass_word = ?", [username, password]);
    result = count;
    if (count == 0) {
      int res = await db.insert(_TABLE_NAME, {"user_name": username, "pass_word": password, "login_count": 1});
      result = res;
    }
    return result;
  }


  ///删除所有
  Future<int> deleteAll() async {
    var db = await DatabaseHelper().db();
    int result = 0;
    result = await db.delete(_TABLE_NAME);
    return result;
  }
}
